package com.one.rope.mvp.basecore.third.wx.miniprogram;

import com.one.rope.mvp.basecore.util.HttpRequestUtil;
import com.one.rope.mvp.basecore.util.JsonUtils;
import java.util.HashMap;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 *   微信小程序工具类
 * <p>
 *
 * @author ： Weijian.Liu
 * @date ： 2020/3/11 23:35
 */
@Slf4j
public class WxMiniprogramUtil {

  private static String appId = "wx76e5abc630337e6d";
  private static String appSecret = "61c3c6edc9eebde604d4881095a0cbb2";
  private static String code2SessionUrl = "https://api.weixin.qq.com/sns/jscode2session";

  /**
   * 小程序登录授权类型
   */
  private static final String authoGrantType = "authorization_code";

  /**
   * 微信小程序登录授权
   * @param reqVO
   * @return
   */
  public static MiniprogramAuthoResVO wxMiniprogramLogin(MiniprogramAuthoReqVO reqVO){
    MiniprogramAuthoResVO resVO = new MiniprogramAuthoResVO();
    Map<String, String> params = new HashMap<>();
    params.put("appid", reqVO.getAppId());
    params.put("secret", reqVO.getAppSecret());
    params.put("js_code", reqVO.getCode());
    params.put("grant_type", authoGrantType);
    try {
      String response = HttpRequestUtil.sendGetRequest(reqVO.getCode2SessionUrl(), params);
      resVO = JsonUtils.stringToFasterxmlObject(response, MiniprogramAuthoResVO.class);
      if(null != resVO.getErrcode()){
        log.error("微信小程序授权失败，原因: {}", resVO.getErrmsg());
      }
    }catch (Exception e){
      log.error("微信小程序授权失败，原因: {}", e);
    }
    return resVO;
  }

  public static void main(String[] args) {
    MiniprogramAuthoReqVO reqVO = new MiniprogramAuthoReqVO();
    reqVO.setAppId(appId);
    reqVO.setAppSecret(appSecret);
    reqVO.setCode("043u5zq52KH72S0NIen52tJCq52u5zqQ");
    reqVO.setCode2SessionUrl(code2SessionUrl);
    System.out.println(wxMiniprogramLogin(reqVO).getOpenid());
  }
}
